/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author antonio
 */
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;


public class InformationProcessing {
	public static CharSequence binarize(int img[][], int level)
	{
		final int len = img.length;
		String bw = "";
		for(int i=0; i < len; i++)
		{
			for(int j=0; j < len; j++)
			{
				if(img[i][j] > level)
					bw += "1";
				else
					bw += "0";
				//bw += img[i][j];
			}
		}
		//System.out.println(bw);
		return bw;
	}
	
	public static CharSequence discretize(int img[][], int level)
	{
		final int len = img.length;
		String ds = "";
		int l;
		for(int i=0; i < len; i++)
		{
			for(int j = 0; j < len; j++)
			{
				l = -1;
				for(int k = 0; k <= img[i][j] ; k += 256/level)
				{	
					l = l+1;//System.out.println(l);
				}
				//System.out.println("out: " + l);
				ds += (new Integer(l)).toString();	
			}
		}
		//System.out.println(ds);
		return ds;
	}
	
	public static int byteArrayToInt(byte[] b) 
	{
        return byteArrayToInt(b, 0);
    }
	
	public static int byteArrayToInt(byte[] b, int offset) 
	{
	    int value = 0;
	    for (int i = 0; i < 4; i++) 
	    {
	    	int shift = (4 - 1 - i)* 8;
	        value += (b[i + offset] & 0x000000FF) << shift;
	    }
	    return value;
	}
	
	public static void main(String[] args) {
		try{
			MnistManager mnist = new MnistManager("/home/antonio/Downloads/train-images.idx3-ubyte","/home/antonio/Downloads/train-labels.idx1-ubyte");
			//MnistManager mnistTest = new MnistManager("/home/antonio/Downloads/t10k-images.idx3-ubyte","/home/antonio/Downloads/t10k-labels.idx1-ubyte");
			final String DATE_FORMAT_NOW = "yyyy-MM-dd--HH:mm:ss";
			Calendar cal = Calendar.getInstance();
		    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
		    File fa = new File("/home/antonio/outputHierarchies/out" + sdf.format(cal.getTime()) + ".txt");
			FileWriter fstream = new FileWriter(fa);
			BufferedWriter fout = new BufferedWriter(fstream);
			int hierOrder[] = {25,50,15,1};
			int markovOrder = 5;
			ICNN hrc = new ICNN(4,hierOrder,markovOrder);
			int image[][];
			int trials = 100;
			int label[] = new int[trials];
			for(int i = 11; i <= trials; i++)
			{
				//mnist.setCurrent(i%11 + 1);
				mnist.setCurrent(i);
				image = mnist.readImage();
				label[i-1] = mnist.readLabel();
				//if(label[i-1] == 0 || label[i-1] == 1)
				if(label[i-1] < 2)
				{
					//mnist.writeImageToPpm(image, "/home/antonio/mnist/" + i + "-" + label[i-1] + ".ppm");
					//System.out.println(i);
					//CharSequence bw = binarize(image,80);
					CharSequence bw = discretize(image,2);
					//System.out.println(bw);
					hrc.feed(bw);
					hrc.evolve();
					System.out.println(label[i-1] + " - " + hrc.response());
					
				}
			}
			fout.close();
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}
